import { getSimcardList, getSimExportUrl, getVehInfo, getVehExportUrl } from '../services/api';

export default {
    namespace: 'vehicle',

    state: {
        list: [],
        filteredList: [], // used by modal list display
        onDevNum: 0,
        total: 0,
        pagination: {
            current: 1,
            pageSize: 10,
            total: 0,
        },
        filteredPagination: {
            current: 1,
            pageSize: 10,
        },
        isLoading: false,
        hasMore: false,
    },
    effects: {

        *fetchVehInfo({ payload }, { call, put }) {

            const rsp = yield call(getVehInfo, payload);

            yield put({
                type: 'setList',
                payload: rsp,
            });

            yield put({
                type: 'setLoading',
                payload: false,
            });
        },
        *onExport({ payload, callback }, { call, put }) {
            const rsp = yield call(getVehExportUrl, payload);

            if (callback) callback(rsp.expVehPeriodOpts.expFileUrl);
        }
    },
    reducers: {
        setList(state, action) {
            const { pagination } = state
            return {
                ...state,
                list: action.payload.vehPeriodOpts,
                pagination: { ...pagination, total: action.payload.pageInfo.pageTotal, current: action.payload.pageInfo.curPageNum },
            };
        },
        setFilteredList(state, action) {
            return {
                ...state,
                filteredList: [...state.filteredList, ...action.payload.list],
                hasMore: action.payload.hasMore,
            };
        },
        setPagination(state, action) {
            return {
                ...state,
                pagination: {
                    ...state.pagination,
                    current: action.payload,
                },
            };
        },
        setLoading(state, action) {
            return {
                ...state,
                isLoading: action.payload,
            };
        },
        setFilteredPagination(state, action) {
            return {
                ...state,
                filteredPagination: {
                    ...state.filteredPagination,
                    current: action.payload,
                },
            };
        },
        resetFilteredList(state) {
            return {
                ...state,
                filteredList: [],
                filteredPagination: {
                    current: 1,
                    pageSize: 10,
                },
            };
        },
    },
};
